﻿using System;
using System.Threading;
using NUnit.Framework;
using Smith.AMC;

namespace MemcachedClientTests
{
    public class TestHelper
    {

        public static void SetValueInServer<T>(IMemcachedClient client, ICacheItem<T> cacheItem)
        {
            ManualResetEvent evt = new ManualResetEvent(false);
            bool success = false;
            client.BeginSet(
                new CacheItem<string>
            {
                CacheKey = "setTest",
                Value = "This is the set value",
                LifeTime = TimeSpan.FromMinutes(20)
            },
            ar =>
            {
                ManualResetEvent evtInner = (ManualResetEvent)ar.AsyncState;
                try
                {
                    success = client.EndSet<string>(ar);
                }
                finally
                {
                    evtInner.Set();
                }
            },
            evt);

            evt.WaitOne();

            Assert.That(success, Is.True);
        }

        public static T GetValueFromServer<T>(IMemcachedClient client, string cacheKey)
        {
            ManualResetEvent evt2 = new ManualResetEvent(false);
            ICacheItem<T> itemRetrieved = null;
            client.BeginGet<T>(
                cacheKey,
                ar =>
                {
                    ManualResetEvent evtInner = (ManualResetEvent)ar.AsyncState;
                    try
                    {
                        itemRetrieved = client.EndGet<T>(ar);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                    evtInner.Set();
                }, 
                evt2);
            evt2.WaitOne();

            Assert.IsNotNull(itemRetrieved);
            return itemRetrieved.Value;
        }
    }
}
